<?php
class Address_model extends CI_Model {
	public $id;
	public $user_id;
	public $consignee;
	public $country;
	public $province;
	public $city;
	public $address;
	public $zipcode;
	public $mobile;
	public $telephone;
	public $default;
	
	private $areas;
	
    function __construct()
    {
        parent::__construct();
    }
    
    //添加一条地址
    function add($data)
    {       
		if($olddata = $this->getDefaultOne($data['user_id']))
			$this->db->update('address', $data,array('id'=>$olddata['id']));
		else
		{
			$data['default'] = 1;
			$this->db->insert('address', $data); 
		}
    }
    
    
	
    //获得所有地址
    function getAll($user_id)
    {
		$query = $this->db->get_where('order_goods',array('user_id'=>$user_id));
	    return $query->result('Address_model');
    }
    
    function getDefaultOne($user_id)
    {
    	$query = $this->db->get_where('address',array('user_id'=>$user_id,'default' => 1));
    	return $query->row_array();
    }
	
    //删除地址记录
    function delete($id)
    {
		$this->db->delete('order_goods', array('id' => $id)); 
    }
    
    //修改
    function update($id,$data)
    {
        $this->db->update('order_goods', $data, array('id' => $id));
    }
    
    //设置默认
    function setDefault($user_id,$id)
    {    	
    	$this->db->update('order_goods', array('default'=> 0), array('user_id' => $user_id));
    	$this->db->update('order_goods', array('default'=> 1), array('id' => $id));
    }
    
    //获得地址
    function getOne($id)
    {
    	$query = $this->db->get_where('order_goods',array('id'=>$id));
    	return $query->row_array();
    }
    
    function getAreas()
    {
    	if(!$this->areas)
    	{
    		include_once (APPPATH.'config/areas.php');
    		$this->areas = $areas;
    	}
    	return $this->areas;
    }
    
    function getAreasById($pid,$cid,$zid)
    {
    	$areas = $this->getAreas();    	
    	if(isset($areas[$pid]) && isset($areas[$pid]['c'][$cid]) && isset($areas[$pid]['c'][$cid]['c'][$zid]))
    	{
    		return $areas[$pid]['name'].$areas[$pid]['c'][$cid]['name'].$areas[$pid]['c'][$cid]['c'][$zid]['name'];
    	}
    	return false;
    	
    }
}